package others;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * 循环路障限流
 */
public class CyclicBarrierTest {
    public static void main(String[] args) throws InterruptedException {
        //当线程打到5个时进行限制
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println("人满，发车!"));
        for (int i = 0; i < 11; i++) {
            TimeUnit.SECONDS.sleep(1);
            new Thread(() -> {
                try {
                    cyclicBarrier.await();
                    System.out.println("结束" + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
